//
//  HOself.audioPlayer.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/7/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "Logger.h"
#import "HOUtils.H"


@interface HOAudioPlayer()<AVAudioPlayerDelegate>
{
	
	
}
@property(nonatomic, retain)NSTimer *timer;
@property(nonatomic, assign)NSTimeInterval totalPlayTime;
@property(nonatomic, assign)BOOL isAudioConverted;
@property(nonatomic, retain)AVAudioPlayer *audioPlayer;

@end

@implementation HOAudioPlayer
@synthesize delegate;
@synthesize voicePath;
@synthesize playStatus;
- (instancetype)init
{
	self = [super init];
	if(self)
	{
	}
	return self;
}

- (BOOL)initAudioPlayerForWav
{
	if(self.audioPlayer)
	{
		[self cleanup];
	}
	if(self.voicePath == nil)
	{
		return NO;
	}
	NSError* err;
	//        LogNor(@"audio.voiceData:%@", _audio.voiceData);
	self.audioPlayer = [[[AVAudioPlayer alloc]
				   initWithContentsOfURL:[NSURL URLWithString:self.voicePath]
				   error:&err ] autorelease];
	
	UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
	AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
							sizeof(sessionCategory),
							&sessionCategory);
	
	UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
	AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
							 sizeof (audioRouteOverride),
							 &audioRouteOverride);
	
	AVAudioSession *audioSession = [AVAudioSession sharedInstance];
	//默认情况下扬声器播放
	[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
	[audioSession setActive:YES error:nil];
	
	
	[self.audioPlayer setDelegate:self];
	//        LogNor(@"self.audioPlayer.delegate:%@", self.audioPlayer.delegate);
	self.audioPlayer.meteringEnabled = YES;
	[self.audioPlayer prepareToPlay];
	return YES;
}

- (void)cleanup
{
	if(self.audioPlayer)
	{
		self.audioPlayer.delegate = nil;
		self.audioPlayer = nil;
	}
}
#pragma mark
- (void)stopAudio
{
	//    if(self.playStatus == AUDIO_STOPED)
	//    {
	//        [self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
	//        [self stopTimer];
	//        return;
	//    }
	[self.audioPlayer playAtTime:0.1];
	if(self.audioPlayer.isPlaying)
	{
		[self.audioPlayer stop];
	}
	self.playStatus = AUDIO_STOPED;
	[self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
	[self stopTimer];
}

- (void)resetPlayer
{
	[self stopAudio];
	[self cleanup];
	[self initAudioPlayerForWav];
}

- (void)playAudio
{
	if(self.audioPlayer == nil)
	{
		[self initAudioPlayerForWav];
	}
//	[self updateMediaMsgReadStatus];
	switch (self.playStatus) {
		case AUDIO_PLAYING:
		{
			[self stopAudio];
		}
			break;
		case AUDIO_STOPED:
		{
			LogNor(@"self.audioPlayer.delegate1:%@", self.audioPlayer.delegate);
			if(self.audioPlayer.delegate == nil)
			{
				[self.audioPlayer setDelegate:self];
			}
			LogNor(@"self.audioPlayer.delegate2:%@", self.audioPlayer.delegate);
			if(!self.audioPlayer.isPlaying)
			{
				[self.audioPlayer play];
			}
			//[self initSpeaker:YES];
			self.playStatus = AUDIO_PLAYING;
			[self startTimer];
			[self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
			
		}
			break;
			
		default:
			break;
	}
}

#pragma mark AVAudioPlayerDelegate methods
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//	LogNor(@"self.audioPlayer--DidFinishPlaying:");
	[self stopAudio];
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
	LogNor(@"self.audioPlayer--EndInterruption:");
	self.playStatus = AUDIO_ERROR;
	[self stopTimer];
	[self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
}

#pragma mark - -- timer
- (void)startTimer
{
	if(self.timer == nil)
	{
		self.timer = [NSTimer scheduledTimerWithTimeInterval: .3
												 target: self
											   selector: @selector(handleTimer)
											   userInfo: nil
												repeats: YES];
		
	}
	[self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
}

- (void)handleTimer
{
	if(self.delegate == nil)
	{
		
		self.playStatus = AUDIO_STOPED;
		[self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
		[self stopTimer];
		return;
	}
//	LogNor(@"self.audioPlayer.currentTime:%f totalPlayTime:%f", self.audioPlayer.currentTime,self.totalPlayTime);
	if(self.audioPlayer.currentTime < 0.1)
	{
//		LogNor(@"play finished.-----------");
//		LogNor(@"self.audioPlayer.currentTime:%f", self.audioPlayer.currentTime);
		if(self.audioPlayer.isPlaying)
		{
			[self.audioPlayer stop];
		}
		self.playStatus = AUDIO_STOPED;
		[self stopTimer];
		[HOUtils deleteAudioFromLocal:self.voicePath withFileType:FILE_TYPE_WAV];
		self.isAudioConverted = NO;
	}
	[self.delegate updateAudioIndicateWithPlayWithStatus:self.playStatus];
}
- (void)stopTimer
{
	if(self.timer != nil)
	{
		[self.timer invalidate];
		self.timer = nil;
	}
}

- (void)dealloc
{
	[self stopTimer];
	self.voicePath = nil;
	self.delegate = nil;
	[super dealloc];
}
@end
